#include "types.h"
#include "stat.h"
#include "user.h"
#include "fcntl.h"

static void* blah(void);
static void* blah2(void);
static void* blah3(void);

int t;
int t2;

int
main(int argc,char* argv[])
{
   void *pg;
   void *pg1; 
   int i;
   int sem;
   void* ret;
   sem = binary_sem_create();

   pg = malloc(1024);
   pg1 = malloc(1024);


   printf(2,"creating thread 1 with function: %d\n",blah);
   t=thread_create(&blah,pg,1024);
   printf(2,"finished 1 creating: %d\n",t);
   
   printf(2,"creating thread 2 with function: %d\n",blah);
   t2=thread_create(&blah2,pg1,1024);
   printf(2,"finished 2 creating: %d\n",t);	

	int threads[5];

       for (i=0; i<1; i++){
		void* pg = malloc(1024);
		printf(2, "creating a thread from first thread\n");
		threads[i]= thread_create(&blah3, pg, 1024);
 	}

   int ret2 = thread_join(t2,&ret);

   for (i=0;i<50;i++){
       printf(1,"process iteration %d\n",i);
   }
   

   printf(2,"exit big process ans is %d\n",ret2);
   printf(2, "my process id is %d %d\n", thread_getProcId(), thread_getid());
   thread_exit((char*)ret2);
   //exit();
   return 0;
}



static void*
blah()
{

int i=0;
 char* ret="ffffff";
// void *retThread;

 for(i = 0; i <150; i++){
   printf(2,"thread 1 iteration %d\n",i);
}

//	void* pg = malloc(1024);
//	thread_create(&blah3, pg, 1024);
	//thread_join(threads[0], &retThread);

printf(1,"exit thread 1\n");
  // exit();
   thread_exit(ret);
   return ret;
} 

static void*
blah2()
{

 int i=0;
 char* ret="ffffff";
// void* ret1;

// int jret = thread_join(t,&ret1);
 //if(jret<0){
//	printf(1,"can't do join twice!!!");
//	thread_exit(ret1);	
 //}

 for(i = 0; i <50; i++){
   printf(2,"thread 2 iteration %d\n",i);
}
printf(1,"exit thread 2\n");
   printf(2, "my parent process id is %d\n", thread_getProcId());
   printf(2, "exiting thread 2 who created by main process!!!\n");
   //thread_exit(ret);
   exit();
   return ret;
} 

static void*
blah3()
{

int i=0;
 char* ret="ffffff";

	int pid = fork();
	if (pid!=0)
		wait();
	else
	{
		for(i = 0; i <1500; i++){
			printf(2,"proc %d iteration %d, it was created by thread 1\n", thread_getid(),i);
		}
		printf(1,"I am a child of a thread\n");
	}
	printf(1,"exit thread %d\n", thread_getid());

   thread_exit(ret);
//   exit();
   return ret;
}
